package com.idea.zd.sys.train.thread.producerandconsumer;

import java.util.Date;
import java.util.Queue;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Consumer implements Runnable {

    private Queue<String> product;

    private Lock lock = new ReentrantLock();

    private Condition condition = lock.newCondition();

    public Consumer(Queue<String> product){
        this.product = product;
    }
    /*@Override
    public void run() {
        while(true){
            try{
                lock.lock();
                while(product.size() == 0){
                    condition.await();
                }

                System.out.println(product.poll());
                condition.signal();

            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                lock.unlock();
            }
        }

    }*/

    @Override
    public void run() {
        while(true){
            synchronized (product){
                while(product.size() == 0){
                    try {
                        product.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

                System.out.println(product.poll());
                product.notify();
            }
        }

    }
}
